package com.maotai.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.bean.MaotaiAppCookie;


public class MaotaiAppHttpClientUtil {
	
	private static MaotaiAppHttpClientUtil instance = null;

	private MaotaiAppHttpClientUtil() {
	}

	public static MaotaiAppHttpClientUtil getInstance() {
		if (instance == null) {
			instance = new MaotaiAppHttpClientUtil();
		}
		return instance;
	}
	public MaotaiAppCookie sendHttpGetProxy(String httpUrl, MaotaiAppCookie mwc, String hostname ,int port, String referer) {
		OkHttpClient client = new OkHttpClient();
		client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(hostname, port)));
		Request request = new Request.Builder().url("http://www.163.com").build();

		try {
			Response response = client.newCall(request).execute();//发送请求
			String result = response.body().string();
			Log.d(TAG, "result: "+result);
			show(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sendHttpGetProxy(httpGet,mwc,config);
	}

	private MaotaiAppCookie sendHttpGetProxy(HttpGet httpGet,MaotaiAppCookie mwc, RequestConfig config) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		HttpEntity entity = null;
		String return_str = null;
		try {
			httpClient = HttpClients.createDefault();
			
			httpGet.setConfig(config);
			response = httpClient.execute(httpGet);
			entity = response.getEntity();
			return_str = EntityUtils.toString(entity, "UTF-8");
			mwc.setContent(return_str);
			System.out.println(return_str);
		} catch (Exception e) {
//			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
//				e.printStackTrace();
			}
		}
		return mwc;
	}
	private HttpGet setHttpGetHeader(HttpGet httpGet,MaotaiAppCookie mwc,String referer) {
		httpGet.addHeader("Accept","application/json");
		httpGet.addHeader("appcode","2");
		httpGet.addHeader("Accept-Encoding", "gzip");
		httpGet.addHeader("Connection", "keep-alive");
		httpGet.addHeader("Host", "i.cmaotai.com");
		httpGet.addHeader("tenantid", "1");
//		httpGet.addHeader("channelcode", "02");
		httpGet.addHeader("channelCode", "02");
		httpGet.addHeader("terminaltype", "d1");
		httpGet.addHeader("Content-Type","application/json;charset=UTF-8");
		httpGet.addHeader("User-Agent","okhttp/3.6.0");
		httpGet.addHeader("reqid",System.currentTimeMillis()+"");
		if(mwc.getAuth()!=null && !"".equals(mwc.getAuth())){
			httpGet.addHeader("auth",mwc.getAuth());
		}
		if(mwc.getAcwTc()!=null && !"".equals(mwc.getAcwTc())){
			httpGet.addHeader("Cookie",mwc.getAcwTc());
		}
		if(mwc.getMemberid()!=null && !"".equals(mwc.getMemberid())){
			httpGet.addHeader("memberid",mwc.getMemberid());
		}
		return httpGet;
	}
	private HttpPost setHttpPostHeader(HttpPost httpPost, MaotaiAppCookie mwc ,String referer) {
		httpPost.addHeader("Accept","application/json, text/javascript, */*; q=0.01");
		httpPost.addHeader("appId","1");
		httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.addHeader("Connection", "keep-alive");
		httpPost.addHeader("Host", "i.emaotai.cn");
		httpPost.addHeader("tenantid", "1");
		httpPost.addHeader("channelcode", "01");
		httpPost.addHeader("terminaltype", "d1");

		httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
		httpPost.addHeader("User-Agent","okhttp/3.6.0");
		httpPost.addHeader("reqid",System.currentTimeMillis()+"");
		if(mwc.getAuth()!=null && !"".equals(mwc.getAuth())){
			httpPost.addHeader("auth",mwc.getAuth());
		}

		return httpPost;
	}

    public MaotaiAppCookie sendHttpPostProxy(String httpUrl,MaotaiAppCookie mwc, Map<String, String> maps,RequestConfig requestConfig, String referer) throws Exception {  
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost = setHttpPostHeader(httpPost,mwc,referer);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        for (String key : maps.keySet()) {  
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));  
        }  
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));  
        return sendHttpPostProxy(httpPost,mwc,requestConfig);  
    }
    
    private MaotaiAppCookie sendHttpPostProxy(HttpPost httpPost,MaotaiAppCookie mwc,RequestConfig config) throws Exception{  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;
		String return_str = null;
        httpClient = HttpClients.createDefault(); 
        httpPost.setConfig(config);  
        response = httpClient.execute(httpPost); 
        entity = response.getEntity();
		return_str = EntityUtils.toString(entity, "UTF-8");
		mwc.setContent(return_str);
		System.out.println(return_str);
        Header[] headers = response.getAllHeaders();
        if(headers!=null&&headers.length>0){
        	for (Header hea : headers) {
//        		System.out.println(hea.getName() + "::::::::::::::"
//						+ hea.getValue());
				if(hea.getName().contains("auth")){
					mwc.setAuth(hea.getValue());
				}
			}
        }
        if (response != null) {  
            response.close();  
        }  
        if (httpClient != null) {  
            httpClient.close();  
        }  
        return mwc;  
    } 

}